<template>
  <div class="category-container">
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <span>我的预约记录</span>
          <el-radio-group v-model="statusFilter" @change="handleStatusFilterChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="confirmed">已通过</el-radio-button>
            <el-radio-button label="pending">待通过</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <!-- 添加加载状态 -->
      <div v-loading="loading">
        <el-table :data="filteredAppointments" style="width: 100%" border>
          <el-table-column label="序号" width="80">
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="date" label="日期" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间" width="120" />
          <el-table-column prop="coach" label="教练" width="120" />
          <el-table-column prop="program" label="训练项目" />
          <el-table-column prop="status" label="状态" width="120" sortable>
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleViewDetails(scope.row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleCancel(scope.row)"
                :disabled="!canCancel(scope.row)"
              >
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          class="pagination"
          v-model:current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="totalAppointments"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 预约详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="预约详情" width="50%">
        <div v-if="selectedAppointment" class="appointment-detail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="预约编号">
              {{ selectedAppointment.id }}
            </el-descriptions-item>
            <el-descriptions-item label="训练项目">
              {{ selectedAppointment.program }}
            </el-descriptions-item>
            <el-descriptions-item label="教练">
              {{ selectedAppointment.coach }}
            </el-descriptions-item>
            <el-descriptions-item label="日期">
              {{ formatDate(selectedAppointment.date) }}
            </el-descriptions-item>
            <el-descriptions-item label="时间">
              {{ selectedAppointment.time }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(selectedAppointment.status)">
                {{ getStatusText(selectedAppointment.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ selectedAppointment.createdAt }}
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              {{ selectedAppointment.notes || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 创建axios实例，配置基础URL
const apiClient = axios.create({
  baseURL: 'http://127.0.0.1:8000', // FASTAPI默认运行在8000端口
  timeout: 10000,
})

// 数据和状态
const appointments = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10) // 固定每页10条
const statusFilter = ref('all')

// 学生ID（需要从实际用户信息中获取）
const studentId = ref('')

// 对话框
const detailDialogVisible = ref(false)
const selectedAppointment = ref(null)

// 分页和过滤
const filteredAppointments = computed(() => {
  let result = [...appointments.value]

  // 状态过滤
  if (statusFilter.value !== 'all') {
    result = result.filter(item => item.status.toLowerCase() === statusFilter.value)
  }

  // 分页
  return result.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
})

const totalAppointments = computed(() => {
  let result = appointments.value

  if (statusFilter.value !== 'all') {
    result = result.filter(item => item.status.toLowerCase() === statusFilter.value)
  }

  return result.length
})

// 分页处理
const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleStatusFilterChange = () => {
  currentPage.value = 1
}

// 状态处理
const getStatusType = (status) => {
  const statusValue = status?.toLowerCase()
  switch (statusValue) {
    case 'confirmed':
      return 'success'
    case 'pending':
      return 'warning'
    case 'completed':
      return ''
    case 'cancelled':
      return 'info'
    default:
      return ''
  }
}

const getStatusText = (status) => {
  const statusValue = status?.toLowerCase()
  switch (statusValue) {
    case 'confirmed':
      return '已通过'
    case 'pending':
      return '待通过'
    default:
      return status
  }
}

const canCancel = (appointment) => {
  const status = appointment.status?.toLowerCase()
  return ['confirmed', 'pending'].includes(status)
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 对话框操作
const handleViewDetails = (appointment) => {
  selectedAppointment.value = appointment
  detailDialogVisible.value = true
}

const handleCancel = (appointment) => {
  ElMessageBox.confirm(`确定要取消【${appointment.program}】预约吗？`, '取消预约', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用后端API取消预约
      await apiClient.put(`/appointment/cancel/${appointment.id}`)

      // 更新本地状态
      appointment.status = 'cancelled'
      ElMessage.success('预约已取消')
    } catch (error) {
      ElMessage.error('取消预约失败: ' + (error.message || '未知错误'))
      console.error('取消预约失败:', error)
    }
  }).catch(() => {
  })
}

// 获取预约数据
const fetchAppointments = async () => {
  // 检查是否有学生ID
  if (!studentId.value) {
    ElMessage.warning('未获取到用户信息')
    return
  }

  loading.value = true
  try {
    // 使用配置好的axios实例调用API
    const response = await apiClient.get(`/appointment/msg/${studentId.value}`)

    // 根据实际返回的数据结构处理数据
    if (response.data && response.data.data) {
      // 提取实际的预约数据并转换为前端需要的格式
      const rawData = response.data.data

      // 转换数据格式以匹配前端组件的需求
      appointments.value = rawData
        // 过滤掉已取消的预约
        .filter(item => item.status?.toLowerCase() !== 'cancelled')
        .map(item => ({
          id: item.appointment_id,
          date: item.appointment_date,
          time: formatTimeRange(item.start_time, item.end_time),
          coach: item.coach?.fullname || `教练${item.coach?.id || '未知'}`,
          program: item.program?.name || `项目${item.program?.id || '未知'}`,
          status: item.status?.toLowerCase() || 'unknown',
          createdAt: new Date().toISOString(), // 你可能需要从后端获取实际创建时间
          notes: '' // 你可能需要从后端获取备注信息
        }))
    } else {
      // 如果没有数据，设置为空数组
      appointments.value = []
      ElMessage.info('暂无预约记录')
    }
  } catch (error) {
    ElMessage.error('获取预约信息失败: ' + (error.message || '未知错误'))
    console.error('获取预约信息失败:', error)
    appointments.value = [] // 设置为空数组以避免后续错误
  } finally {
    loading.value = false
  }
}

// 添加时间格式化函数
const formatTimeRange = (startTime, endTime) => {
  try {
    // 处理时间格式 "HH:MM:SS"，只需要 "HH:MM"
    const formatTime = (timeString) => {
      if (!timeString || typeof timeString !== 'string') {
        return '--:--'
      }

      // 分割时间字符串并取前两部分（小时和分钟）
      const parts = timeString.split(':')
      if (parts.length >= 2) {
        return `${parts[0]}:${parts[1]}`
      }
      return '--:--'
    }

    return `${formatTime(startTime)}-${formatTime(endTime)}`
  } catch (error) {
    console.error('格式化时间出错:', error, { startTime, endTime })
    return '--:--'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  // 从localStorage获取学生ID
  studentId.value = localStorage.getItem('user_id')

  // 如果localStorage中没有user_id，则使用默认值进行测试
  if (!studentId.value) {
    studentId.value = '5' // 使用默认值
    ElMessage.warning('未找到用户ID，使用默认ID进行测试')
  }

  // 获取预约数据
  fetchAppointments()
})
</script>

<style lang="scss" scoped>
.category-container {
  padding: 20px 0;

  .category-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}

.appointment-detail {
  padding: 10px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
